﻿using System;
using System.Collections.Generic;
using System.Text;
using IBatisNet.DataMapper;
using IBatisNet.DataMapper.MappedStatements;
using IBatisNet.DataMapper.Scope;
using System.Data;
using IBatisNet.DataMapper.Configuration.Statements;
using IBatisNet.Common;

namespace OneMG.Phoenix.Kernel.IBatisUtil
{

	public abstract class BaseIBatisDao
	{
		#region Properties

		public ISqlMapper SqlMapper { get; set; }

		#endregion

		#region Constructor

		public BaseIBatisDao()
		{
		}

		public BaseIBatisDao(string mapperName)
		{
			this.SqlMapper = SqlMapperManager.GetMapper(mapperName);
		}

		#endregion

		#region Functions

		/// <summary>
		/// 得到运行时ibatis.net动态生成的SQL
		/// </summary>
		/// <param name="sqlMapper"></param>
		/// <param name="statementName"></param>
		/// <param name="paramObject"></param>
		/// <returns></returns>
		public virtual string GetRuntimeSql(string statementName, object paramObject)
		{
			string result = string.Empty;
			try
			{
				IMappedStatement statement = SqlMapper.GetMappedStatement(statementName);
				if (!SqlMapper.IsSessionStarted)
				{
					SqlMapper.OpenConnection();
				}
				RequestScope scope = statement.Statement.Sql.GetRequestScope(statement, paramObject, SqlMapper.LocalSession);
				result = scope.PreparedStatement.PreparedSql;


			}
			catch (Exception ex)
			{
				result = "获取SQL语句出现异常:" + ex.Message;
			}
			return result;
		}



		/// <summary>
		/// 获取DataTable
		/// </summary>
		/// <param name="tag">statementName</param>
		/// <param name="paramObject">语句所需要的参数</param>
		/// <returns>得到的DataTable</returns>
		public DataTable GetDataTable(string statementName, object paramObject)
		{


			bool isSessionLocal = false;
			ISqlMapSession session = SqlMapper.LocalSession;
			DataTable dataTable = null;

			if (session == null)
			{

				session = SqlMapper.CreateSqlMapSession();
				isSessionLocal = true;
			}

			try
			{
				IMappedStatement statement = SqlMapper.GetMappedStatement(statementName);
				dataTable = new DataTable(statementName);
				RequestScope request = statement.Statement.Sql.GetRequestScope(statement, paramObject, session);
				statement.PreparedCommand.Create(request, session, statement.Statement, paramObject);

				using (request.IDbCommand)
				{
					dataTable.Load(request.IDbCommand.ExecuteReader());

				}


			}
			catch
			{
				throw;
			}
			finally
			{
				if (isSessionLocal)
				{
					session.CloseConnection();
				}
			}

			return dataTable;

		}



		#endregion

	}
}
